#include "chooselevelscene.h"
#include <QMenu>
#include <QMenuBar>
#include <QPainter>
#include <mypushbutton.h>
#include <QTimer>
#include <QLabel>
#include <QSound>

ChooseLevelScene::ChooseLevelScene(QWidget *parent) : QMainWindow(parent)
{
    //设置窗口固定大小
    this->setFixedSize(320,588);
    //设置图标
    this->setWindowIcon(QPixmap(":/res/Coin0001.png"));
    //设置标题
    this->setWindowTitle("选择关卡");
    //创建菜单栏
    QMenuBar*bar=this->menuBar();
    this->setMenuBar(bar);
    //创建开始菜单
    QMenu*startMenu=bar->addMenu("开始");
    //创建按钮菜单项
    QAction*quitAction=startMenu->addAction("退出");
    //点击退出 退出游戏
    connect(quitAction,&QAction::triggered,[=](){this->close();});

    //选择关卡按钮音效
    QSound*chooseSound=new QSound(":/res/TapButtonSound.wav",this);
    //返回按钮音效
    QSound*backSound=new QSound(":/res/BackButtonSound.wav",this);


    //返回按钮
    MyPushButton*closeBtn=new MyPushButton(":/res/BackButton.png",":/res/BackButtonSelected.png");
    closeBtn->setParent(this);
    closeBtn->move(this->width()-closeBtn->width(),this->height()-closeBtn->height());

    //返回按钮功能实现
    connect(closeBtn,&MyPushButton::clicked,[=](){
        //播放音效
        backSound->play();
        QTimer::singleShot(500,this,[=](){
             this->hide();
            //触发自定义信号，关闭自身，该信号写到signals下做声明
            emit this->chooseSceneBack();
        });
    });

    //创建关卡按钮
    for(int i=0;i<20;i++){
        MyPushButton*menuBtn=new MyPushButton(":/res/LevelIcon.png");
        menuBtn->setParent(this);
        menuBtn->move(25+(i%4)*70,130+(i/4)*70);


        //按钮上显示的数字
        QLabel*laber=new QLabel;
        laber->setParent(this);
        laber->setFixedSize(menuBtn->width(),menuBtn->height());
        laber->setText(QString::number(i+1));
        //设置居中
        laber->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        laber->move(25+(i%4)*70,130+(i/4)*70);
        //鼠标事件穿透
        laber->setAttribute(Qt::WA_TransparentForMouseEvents,true);

        //监听选择关卡按钮的信号槽
        connect(menuBtn,&MyPushButton::clicked,[=](){
            //播放音效
            chooseSound->play();
            //游戏场景最好不用复用，直接移除掉创建新的场景
            if(pScene==NULL){
                this->hide();
                //将选择的关卡号传入给PlayerScene
                pScene=new PlayScene(i+1);
                pScene->setGeometry(this->geometry());
                pScene->show();

                connect(pScene,&PlayScene::chooseSceneBack,[=](){
                    this->setGeometry(pScene->geometry());
                    this->show();
                    delete pScene;
                    pScene=NULL;
                });
            }
        });  
    }
}

void ChooseLevelScene::paintEvent(QPaintEvent *){
    QPainter painter(this);
    QPixmap pixmap;
    pixmap.load(":/res/OtherSceneBg.png");
    painter.drawPixmap(0,0,this->width(),this->height(),pixmap);

    //加载标题
    pixmap.load(":/res/Title.png");
    painter.drawPixmap((this->width()-pixmap.width())*0.5,30,pixmap.width(),pixmap.height(),pixmap);
}
